package com.daocao.hua.activity;

import android.annotation.TargetApi;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.allen.library.SuperButton;
import com.daocao.hua.R;
import com.daocao.hua.api.Api;
import com.daocao.hua.api.bean.EmailBindBean;
import com.daocao.hua.api.bean.V3EmailCodeBean;
import com.daocao.hua.constant.UserGlobal;
import com.daocao.hua.util.Network;
import com.daocao.hua.util.RxLifeUtil;
import com.daocao.hua.util.ToastUtil;
import com.daocao.hua.util.UI;
import com.daocao.hua.view.V19FrameLayout;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import butterknife.Unbinder;

/**
 * Created by Administrator on 2018/6/10.
 */

public class V3EmailIdentityActivity extends BaseActivity {
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.edit_email)
    EditText editEmail;
    @BindView(R.id.btn_close)
    ImageView btnClose;
    @BindView(R.id.edit_code)
    EditText editCode;
    @BindView(R.id.btn_send_code)
    TextView btnSendCode;
    @BindView(R.id.btn_submit)
    SuperButton btnSubmit;
    @BindView(R.id.txt_email_success)
    TextView txtEmailSuccess;
    @BindView(R.id.layout_identity_success)
    LinearLayout layoutIdentitySuccess;
    @BindView(R.id.layout_need_identity)
    LinearLayout layoutNeedIdentity;
    private Unbinder unbinder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_email_identity_v3);
        initBar();
        unbinder = ButterKnife.bind(this);
        init();
    }

    private static final int TIME = 60 * 1000;  //验证码倒计时时间
    private CountDownTimer timer = new CountDownTimer(TIME, 1000) {

        @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
        @Override
        public void onTick(long millisUntilFinished) {
            try {
                btnSendCode.setEnabled(false);
                btnSendCode.setText((millisUntilFinished / 1000) + getResources().getString(R.string.resend));
                btnSendCode.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.gray));
            } catch (Resources.NotFoundException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFinish() {
            resetBtn();
        }
    };

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void resetBtn() {
        if (timer != null) timer.cancel();
        btnSendCode.setEnabled(true);
        btnSendCode.setText(getResources().getString(R.string.send_code_again));

    }

    private void init() {
        txtTitle.setText("邮箱认证");
        editEmail.setText(UserGlobal.getEmail());
    }

    @OnTextChanged({R.id.edit_email, R.id.edit_code})
    void afterTextChanged(Editable s) {
        if (!TextUtils.isEmpty(UI.toString(editEmail)) && !TextUtils.isEmpty(UI.toString(editCode))) {
            btnSubmit.setShapeSolidColor(0xff4C81FF).setUseShape();
        } else {
            btnSubmit.setShapeSolidColor(0xffE4E4EE).setUseShape();
        }
    }


    private void getEmailCode(String email) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }
        loadingDialog.show();
        V3EmailCodeBean bean = new V3EmailCodeBean();
        bean.email = email;
        Api.api_service.getEmailCode(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    timer.start();
                    ToastUtil.makeText(this, "验证码发送成功，请注意查收");
                });
    }

    private void getEmailBind(String email, String code) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }
        btnSubmit.setShapeSolidColor(0xffFF7A31).setUseShape();
        btnSubmit.setText("认证中...");
        EmailBindBean bean = new EmailBindBean();
        bean.email = email;
        bean.vscode = code;
        Api.api_service.getEmailBind(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        btnSubmit.setShapeSolidColor(0xff4C81FF).setUseShape();
                        btnSubmit.setText("认证中");
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    ToastUtil.makeText(this, "认证成功");
                    layoutNeedIdentity.setVisibility(View.GONE);
                    layoutIdentitySuccess.setVisibility(View.VISIBLE);
                    txtEmailSuccess.setText(email);
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        unbinder.unbind();
        unbinder = null;
    }

    //邮箱验证
    public static boolean isEmail(String strEmail) {
        String strPattern = "^[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]\\.[a-zA-Z][a-zA-Z\\.]*[a-zA-Z]$";
        if (TextUtils.isEmpty(strPattern)) {
            return false;
        } else {
            return strEmail.matches(strPattern);
        }
    }

    @OnClick({R.id.btn_back, R.id.btn_close, R.id.btn_send_code, R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                finish();
                break;
            case R.id.btn_close:
                editEmail.setText("");
                break;
            case R.id.btn_send_code:
                if (!isEmail(UI.toString(editEmail))) {
                    ToastUtil.makeText(this, "邮箱格式不正确");
                    return;
                }
                getEmailCode(UI.toString(editEmail));
                break;
            case R.id.btn_submit:
                if (!isEmail(UI.toString(editEmail))) {
                    ToastUtil.makeText(this, "邮箱格式不正确");
                    return;
                }
                if (TextUtils.isEmpty(UI.toString(editCode))) {
                    ToastUtil.makeText(this, "验证码不能为空");
                    return;
                }
                getEmailBind(UI.toString(editEmail), UI.toString(editCode));
                break;
        }
    }
}
